package cn.lexi.vip.service.user.impl;

import cn.lexi.vip.Constants;
import cn.lexi.vip.entity.User;
import cn.lexi.vip.repository.IUserRepository;
import cn.lexi.vip.service.user.IUserService;
import cn.lexi.vip.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.sql.Timestamp;

/**
 * Created by gaoxiang on 16/11/13.
 */
@Service
public class UserServiceImpl implements IUserService{


    @Autowired
    private IUserRepository userRepository;


    @Override
    public User findByPhoneNo(String phoneNo) {
        return userRepository.findByPhoneNo(phoneNo);
    }

    @Override
    @Transactional(value = Transactional.TxType.REQUIRED)
    public boolean register(String phoneNo, String password, Long registerFrom, String userIp) {
        String uuid ="";
        Timestamp currentTime = new Timestamp(System.currentTimeMillis());

        User user = new User();
        user.setPhoneNo(phoneNo);
        user.setEnable(true);
        user.setRegisteredFrom(registerFrom);
        user.setPassword(PasswordUtil.MD5(password.toLowerCase() + Constants.PASSWORD_SALT));
        user.setUuid(uuid);
        user.setCreatedAt(currentTime);
        user.setUpdatedAt(currentTime);
        userRepository.saveAndFlush(user);

        return exist(phoneNo);
    }

    @Override
    public boolean exist(String phoneNo) {
        User user = userRepository.findByPhoneNo(phoneNo);
        if (user != null) {
            return true;
        }
        return false;
    }
}
